<template>
  <div class="min-h-screen p-2 bg-gradient-to-r from-blue-50 to-blue-100">
    <div class="max-w-5xl mx-auto bg-white rounded-xl shadow-sm overflow-hidden">
      <!-- 标题栏 -->
      <div class="bg-blue-600 px-6 py-4">
        <h1 class="text-xl font-semibold text-white">区域经理物流残次审核</h1>
      </div>

      <!-- 主要内容区 -->
      <div class="p-4 space-y-6">
        <!-- 第一行：基本信息 -->
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div class="space-y-1">
            <p class="text-xl font-semibold text-gray-500">门店名称</p>
            <p class="font-medium text-xl">{{ formData.storeName || '--' }}</p>
          </div>
          <div class="space-y-1">
            <p class="text-xl font-semibold text-gray-500">提报人</p>
            <p class="font-medium text-xl">{{ formData.staffName || '--' }}</p>
          </div>
          <div class="space-y-1">
            <p class="text-xl font-semibold text-gray-500">残次单号</p>
            <p class="font-medium text-xl">{{ formData.billId || '--' }}</p>
          </div>
          <div class="space-y-1" v-if="formData.oaBillId">
            <p class="text-xl font-semibold text-gray-500">钉钉单号</p>
            <p class="font-medium text-xl">{{ formData.oaBillId }}</p>
          </div>
        </div>

        <!-- 第二行：商品信息 -->
        <div class="grid grid-cols-2 md:grid-cols-5 gap-4">
          <div class="space-y-1">
            <p class="text-xl font-semibold text-gray-500">商品名称</p>
            <p class="font-medium text-xl">{{ formData.itemName || '--' }}</p>
          </div>
          <div class="space-y-1">
            <p class="text-xl font-semibold text-gray-500">商品编号</p>
            <p class="font-medium text-xl">{{ formData.itemId || '--' }}</p>
          </div>
          <div class="space-y-1">
            <p class="text-xl font-semibold text-gray-500">商品品类</p>
            <p class="font-medium text-xl">{{ formData.className || '--' }}</p>
          </div>
          <div class="space-y-1">
            <p class="text-xl font-semibold text-gray-500">商品价格</p>
            <p class="font-medium text-xl text-red-600">{{ formData.sellPrice ? `¥${formData.sellPrice}` : '--' }}</p>
          </div>
          <div class="space-y-1">
            <p class="text-xl font-semibold text-gray-500">残次品数量</p>
            <p class="font-medium text-xl text-red-600">{{ formData.posQty }}</p>
          </div>
        </div>

        <div class="grid grid-cols-2 md:grid-cols-5 gap-4">
          <div class="space-y-1">
            <p class="text-xl font-semibold text-gray-500">运单号</p>
            <p class="font-medium text-xl" style="color: red">{{ formData.ydh !== ' ' ?  formData.ydh : '无' }}</p>
          </div>
          <div class="space-y-1">
            <p class="text-xl font-semibold text-gray-500">箱号</p>
            <p class="font-medium text-xl" style="color: red">{{ formData.xh !== ' ' ? formData.xh : '无' }}</p>
          </div>
        </div>
<!--        <div class="flex gap-4 text-center justify-center">-->
<!--          <p class="text-xl font-semibold text-gray-500 ">审批状态</p>-->
<!--          <p class="font-medium text-xl">门店已确认</p>-->
<!--        </div>-->
        <div class="flex gap-4 text-center justify-center">
          <p class="text-xl font-semibold text-gray-500 ">残次审核状态</p>
          <p class="font-medium text-xl" v-if="formData.shStatus === '999'">已终止</p>
          <p class="font-medium text-xl" v-if="formData.shStatus === '000'">门店未确认</p>
          <p class="font-medium text-xl" v-if="formData.shStatus === '001'">门店已确认</p>
          <p class="font-medium text-xl" v-if="formData.shStatus === '002'">区域经理已审核</p>
          <p class="font-medium text-xl" v-if="formData.shStatus === '003'">物流部已审核</p>
        </div>

        <div class="flex gap-4 text-center justify-center" v-if="formData.status === '004'">
          <p class="text-xl font-semibold text-gray-500  ">报废审核状态</p>
          <p class="font-medium text-xl" v-if="formData.status === '004'" style="color: red">已审核</p>
        </div>

        <div class="flex gap-4 text-center justify-center" v-if="formData.wlBillId">
          <p class="text-xl font-semibold text-gray-500 ">物流单号</p>
          <p class="font-medium text-xl">{{ formData.wlBillId }}</p>
        </div>
        <div class="flex gap-4 text-center justify-center">
          <p class="text-xl font-semibold text-gray-500 ">提报时间</p>
          <p class="font-medium text-xl">{{ formData.uptime || '2023-06-15 14:30' }}</p>
        </div>


        <!-- 第三行：残次描述 -->
        <div class="border rounded-lg p-4">
          <p class="text-xl text-gray-500 mb-2">残次描述</p>
          <p class="text-sm leading-5" style="color: red; font-weight: bold">{{ formData.remark || '--' }}</p>
        </div>

        <!-- 第四行：媒体展示 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div class="border rounded-lg p-4">
            <p class="text-xl text-gray-500 mb-2">残次视频</p>
            <div v-if="formData.fj" class="aspect-video bg-black rounded overflow-hidden">
              <video controls class="w-full h-full">
                <source :src="formData.fj" type="video/mp4">
              </video>
            </div>
            <div v-else class="text-gray-400 text-sm py-8 text-center">
              暂无视频
            </div>
          </div>
        </div>

        <!-- 审核操作 -->
        <div class="flex flex-col sm:flex-row justify-end gap-3 pt-4 border-t">
          <button
              @click="showRejectDialog"
              :disabled="buttonsDisabled"
              :class="[
      'px-4 py-2 text-sm rounded transition',
      buttonsDisabled
        ? 'bg-gray-200 text-gray-500 cursor-not-allowed'
        : 'bg-white border border-red-500 text-red-500 hover:bg-red-50'
    ]"
          >
            区域经理驳回
          </button>
          <button
              @click="handleApprove"
              :disabled="buttonsDisabled"
              :class="[
      'px-4 py-2 text-sm rounded transition',
      buttonsDisabled
        ? 'bg-gray-200 text-gray-500 cursor-not-allowed'
        : 'bg-blue-600 text-white hover:bg-blue-700'
    ]"
          >
            区域经理审核
          </button>
        </div>

        <!-- 驳回原因弹窗 -->
        <div v-if="rejectDialogVisible"
             class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div class="bg-white rounded-lg shadow-xl w-full max-w-md">
            <div class="p-6">
              <h3 class="text-lg font-medium text-gray-900 mb-4">请输入驳回原因</h3>
              <textarea
                  v-model="rejectReason"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                  rows="4"
                  placeholder="请详细说明驳回原因..."
              ></textarea>
              <div class="mt-4 flex justify-end space-x-3">
                <button
                    @click="cancelReject"
                    class="px-4 py-2 text-sm text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
                >
                  取消驳回
                </button>
                <button
                    @click="submitReject"
                    :disabled="rejectLoading"
                    class="px-4 py-2 text-sm text-white bg-red-600 rounded-md hover:bg-red-700 disabled:bg-red-300"
                >
                  {{ rejectLoading ? '提交中...' : '提交驳回' }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import axios from 'axios'
import {useRoute} from "vue-router";
import {ElMessage, ElMessageBox} from "element-plus";

// 获取查询路由
const route = useRoute();


// 响应式数据
const formData = ref({
  storeName: '',
  reporter: '',
  billId: '',
  oaBillId: '',
  itemName: '',
  itemId: '',
  className: '',
  sellPrice: 0,
  uptime: '',
  remark: '',
  fj: '',
  staffId: '',
  areaStaff: '',
  shStatus: '',
  storeId: '',
  cgStaff: '',
  staffName: '',
  wlBillId: '',
  status: '',
  posQty: null
});
// 响应式状态
const rejectDialogVisible = ref(false)
const rejectReason = ref('')
const rejectLoading = ref(false)

const buttonsDisabled = ref(true) // 控制按钮禁用状态

const loading = ref(true)
const error = ref(null)
const prefixUrl = ref("https://mms.mumuso.com:8214/dingTalkWebProject/api/file/")

// 显示驳回弹窗
const showRejectDialog = () => {
  rejectReason.value = ''
  rejectDialogVisible.value = true
}

// 取消驳回
const cancelReject = () => {
  rejectDialogVisible.value = false
}

// 提交驳回
const submitReject = async () => {
  if (!rejectReason.value.trim()) {
    await ElMessageBox.alert('请输入当前残次单【' + formData.value.billId + '】驳回原因!', {
      type: "error",
      confirmButtonText: "确认",
      customClass: "my-custom-error",
    });
    return
  }

  rejectLoading.value = true
  try {
    const response = await axios.post('https://mms.mumuso.com:8214/dingTalkWebProject/reported/rejectReported', {
      billId: formData.value.billId,
      rejectReason: rejectReason.value,
      staffId: formData.value.staffId,
      storeId: formData.value.storeId,
      storeName: formData.value.storeName,
      cgStaff: formData.value.cgStaff,
      itemName: formData.value.itemName,
      remark: formData.value.remark,
      staffName: formData.value.staffName,
      className: formData.value.className,
      areaStaff: formData.value.areaStaff
    })

    if (response.data.code === 200) {
      await ElMessageBox.alert(response.data.msg, {
        type: "success",
        confirmButtonText: "确认",
        customClass: "my-custom-error",
      });
      await fetchDefectDetail(formData.value.billId);
    } else {
      await ElMessageBox.alert(response.data.msg, {
        type: "error",
        confirmButtonText: "确认",
        customClass: "my-custom-error",
      });
    }
  } catch (error) {
    console.error(' 驳回请求失败:', error)
    await ElMessageBox.alert('驳回请求失败' + error, {
      type: "error",
      confirmButtonText: "确认",
      customClass: "my-custom-error",
    });
  } finally {
    rejectLoading.value = false
    rejectDialogVisible.value = false
  }
}
// 获取残次单详情
const fetchDefectDetail = async (billId) => {
  try {
    loading.value = true
    const response = await axios.get(`https://mms.mumuso.com:8214/dingTalkWebProject/reported/getReportedInfo/${billId}`)
    if (response.data.code === 200) {
      formData.value = response.data.data
      // 处理附件URL
      if (formData.value.fj) {
        formData.value.fj = prefixUrl.value + formData.value.fj
      }

      // 检查staffId是否匹配
      const localStaffId = localStorage.getItem("staffId")
      if (formData.value.areaStaff && localStaffId && formData.value.areaStaff.toString() === localStaffId.toString()) {
        buttonsDisabled.value = false // 禁用按钮
      }
    } else {
      ElMessageBox.alert(response.data.msg, {
        type: "error",
        confirmButtonText: "确认",
        customClass: "my-custom-error",
      });
    }

  } catch (err) {
    error.value = err.response?.data?.message || '获取数据失败'
    console.error(' 获取残次单详情失败:', err)
  } finally {
    loading.value = false
  }
}

// 审核通过
const handleApprove = async () => {
  try {



    // 添加确认对话框并等待用户选择
    await ElMessageBox.confirm(
        `确定要通过残次单【${formData.value.billId} 】的审核吗？`,
        '确认通过',
        {
          confirmButtonText: '确定通过',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    // 只有用户点击"确定通过"才会执行到这里
    const response = await axios.put(
        `https://mms.mumuso.com:8214/dingTalkWebProject/reported/approveReported`,
        {
          billId: formData.value.billId,
          staffId: formData.value.staffId,
          storeId: formData.value.storeId,
          storeName: formData.value.storeName,
          cgStaff: formData.value.cgStaff,
          itemName: formData.value.itemName,
          remark: formData.value.remark,
          staffName: formData.value.staffName,
          className: formData.value.className
        },
        {
          headers: {
            'Content-Type': 'application/json'
          }
        }
    )

    if (response.data.code  === 200) {
      await ElMessageBox.alert(response.data.msg, {
        type: "success",
        confirmButtonText: "确认",
        customClass: "my-custom-error",
      });
      await fetchDefectDetail(formData.value.billId);
    } else {
      throw new Error(response.data.msg  || '审核操作失败')
    }

  } catch (error) {
    // 用户点击取消按钮
    if (error === 'cancel' || error.message?.includes('cancel'))  {
      return // 静默退出，不显示错误
    }

    // 处理其他错误
    const errorMsg = error.response?.data?.message  || error.message  || '审核操作失败'
    ElMessage.error(` 审核失败: ${errorMsg}`)
    console.error(' 审核通过失败:', error)
  }
}

// 组件挂载时获取数据
onMounted(() => {
  // 从路由参数中获取残次单号
  const billId = route.query.billId;
  // 获取提报人编号
  const staffId = route.query.staffId;
  localStorage.setItem("staffId", staffId);

  if (billId) {
    fetchDefectDetail(billId)
  } else {
    error.value = '未提供残次单号'
    loading.value = false
  }
});
</script>

<style scoped>
/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}
</style>